import pytest
from typing import Generator
from psycopg2.extensions import cursor
from src.api.shop.goods_manage import GoodsManage
from src.config.settings import DATABASE, URL
from src.utils.db_handler import DBHandler
from src.utils.log import logger


@pytest.fixture(scope="session")
def shop_db(env: str) -> Generator[cursor, None, None]:
    """
    连接SHOP软件数据库的fixture.
    :param env: 环境ID
    :return: Cursor
    """
    db = None
    try:
        if env == "develop":
            db = DBHandler(
                host=DATABASE["SHOP"]["DEVELOP"]["host"],
                port=DATABASE["SHOP"]["DEVELOP"]["port"],
                database=DATABASE["SHOP"]["DEVELOP"]["database"],
                user=DATABASE["SHOP"]["DEVELOP"]["user"],
                password=DATABASE["SHOP"]["DEVELOP"]["password"],
            )
        elif env == "test":
            db = DBHandler(
                host=DATABASE["SHOP"]["TEST"]["host"],
                port=DATABASE["SHOP"]["TEST"]["port"],
                database=DATABASE["SHOP"]["TEST"]["database"],
                user=DATABASE["SHOP"]["TEST"]["user"],
                password=DATABASE["SHOP"]["TEST"]["password"],
            )
        elif env == "production":
            db = DBHandler(
                host=DATABASE["SHOP"]["PRODUCTOIN"]["host"],
                port=DATABASE["SHOP"]["PRODUCTOIN"]["port"],
                database=DATABASE["SHOP"]["PRODUCTOIN"]["database"],
                user=DATABASE["SHOP"]["PRODUCTOIN"]["user"],
                password=DATABASE["SHOP"]["PRODUCTOIN"]["password"],
            )
        conn = db.connect_postgresql()
    except Exception as e:
        logger.error("SHOP数据库连接失败")
        raise e
    else:
        logger.info("SHOP数据库连接成功")
        yield conn.cursor()
        conn.close()
        logger.info("SHOP数据库连接关闭")


@pytest.fixture(scope="session")
def shop_url(env: str):
    """
    获取SHOP软件URL地址的fixture.
    :param env: 环境ID
    :return: URL
    """
    if env == "develop":
        return URL["SHOP"]["DEVELOP"]
    elif env == "test":
        return URL["SHOP"]["TEST"]
    elif env == "production":
        return URL["SHOP"]["PRODUCTION"]


@pytest.fixture(scope="session")
def goodsmng_request(shop_url: str) -> GoodsManage:
    """
    GoodsManage服务请求实例化的fixture.
    :param shop_url: SHOP软件的URL地址
    :return: GoodsManage实例
    """
    goods_mng = GoodsManage(shop_url)
    return goods_mng
